package org.sdnstproject.interlayer.interlayerProxy;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.unix.Socket;

/* - controller log analysis
 * - socket close
 * - receive error msg
 * - has received response msg or not
 * */
public class ResultAnalyzer{
	private static final Logger log = LoggerFactory.getLogger(ResultAnalyzer.class);
	private Configuration config = Configuration.getInstance();
	public volatile boolean isSocketClose = false;
	public volatile boolean isControllerException = false;
	public volatile boolean isReceiveErrorMsg = false;
	public volatile boolean notReceiveResponseMsg = false;
	ArrayList<String> controllerException = new ArrayList<String>();
	public String result = "UNKOWN";
	
	public ResultAnalyzer() {
		
	}

	private static class Single{
		private static final ResultAnalyzer instance = new ResultAnalyzer();
	}
	
	public static ResultAnalyzer getInstance() {
		return Single.instance;
	}
	public void init() {
		isSocketClose = false;
		isControllerException = false;
		isReceiveErrorMsg = false;
		notReceiveResponseMsg = false;
		result = "UNKOWN";
		controllerException.clear();
	}
	public String getResult() {
		if(isSocketClose || isControllerException || isReceiveErrorMsg || notReceiveResponseMsg) {
			result = "FAIL";
		}else {
			result = "PASS";
		}
		return result;
	}
	
	@Override
	public String toString() {
		StringBuilder b = new StringBuilder("ResultAnalyzer: ");
//		b.append("result : ").append(result).append(", ");
		if(isSocketClose) b.append("[socket is closed] ");
		if(isReceiveErrorMsg) b.append("[receive error message] ");
		if(notReceiveResponseMsg) b.append("[controller do not reply] ");
		if(isControllerException) {
			b.append("[controler occur exceptioins : ");
			b.append(controllerException.toString());
			b.append("]");
		}
		return b.toString();
	}

	public void printResultsToTerminnal(String ret, String stra){
		System.out.println("发现一个漏洞如下：");
		System.out.println("测试策略："+stra);
		System.out.println("测试结果："+ret);
		System.out.println("原因分析："+this.toString()+"\n");
		try {
			FileWriter fileWriter = new FileWriter(config.getInterlayer_ROOT()+"/output/logs/resultMin.log",false);
			fileWriter.write("发现一个漏洞如下：\n");
			fileWriter.write("测试策略："+stra + "\n");
			fileWriter.write("测试结果："+ret + "\n");
			fileWriter.write("原因分析："+this.toString()+"\n\n");
			fileWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
